﻿function main(item) {
    const url = item.url;
    
    // 安全获取ID参数（修复第4行）
    const getSafeId = () => {
        try {
            const aid = ku9.getQuery(url, "aid");
            const vid = ku9.getQuery(url, "id");
            return aid || vid || url; // 三重保障机制
        } catch (e) {
            ku9.setCache("last_error", e.message, 60000);
            return url;
        }
    };
    const id = getSafeId();

    // 安全解析域名（增强容错）
    const domain = (() => {
        try {
            return id.startsWith("http") ? new URL(id).hostname : "";
        } catch (e) {
            ku9.setCache("domain_error", id, 60000);
            return "";
        }
    })();

    // 动态请求头配置（智能适配）
    const headers = {
        "User-Agent": domain.match(/(cditv|cbg)\.cn/) ?
            "Mozilla/5.0 (Linux; Android 10; HMA-AL00 Build/HUAWEIHMA-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/88.0.4324.93 Mobile Safari/537.36" :
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
        "Referer": (() => {
            try {
                return new URL(id).origin + "/";
            } catch (e) {
                return "https://nettvpro.xyz/"; // 默认Referer
            }
        })()
    };

    // 增强版播放控制脚本
    const jscode = `
    (function(){
        const startTime = Date.now();
        const MAX_WAIT = 15000;
        const CHECK_INTERVAL = 100;
        let videoFound = false;

        /* 初始化页面环境 */
        const initEnv = () => {
            // 清理干扰元素
            document.querySelectorAll("iframe, script, link, meta, style").forEach(e => e.remove());
            
            // 强制页面样式
            document.documentElement.style.cssText = \`
                background:#000!important;
                margin:0!important;
                padding:0!important;
                overflow:hidden!important;
                width:100vw!important;
                height:100vh!important;
            \`;
            
            document.body.style.cssText = \`
                visibility:hidden!important;
                margin:0!important;
                padding:0!important;
                overflow:hidden!important;
                width:100%!important;
                height:100%!important;
            \`;
        };

        /* 深度视频探测 */
        const videoHunter = (root = document) => {
            const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
            let currentNode;
            while ((currentNode = walker.nextNode())) {
                // Shadow DOM穿透
                if (currentNode.shadowRoot) {
                    const shadowVideo = videoHunter(currentNode.shadowRoot);
                    if (shadowVideo) return shadowVideo;
                }
                // 视频元素检测
                if (currentNode.tagName === "VIDEO" && currentNode.readyState > 0) {
                    return currentNode;
                }
                // 备用检测逻辑
                if (currentNode.querySelector) {
                    const childVideo = currentNode.querySelector("video");
                    if (childVideo && childVideo.readyState > 0) return childVideo;
                }
            }
            return null;
        };

        /* 播放器构造器 */
        const createPlayer = (video) => {
            if(videoFound) return;
            videoFound = true;

            // 清理控制组件（修复CSS选择器）
            ["controls", "control-bar", "vjs-control-bar", "xg-controls"].forEach(cls => {
                document.querySelectorAll(\`[class*="\${cls}"]\`).forEach(e => e.remove());
            });

            // 创建全屏容器
            const container = document.createElement("div");
            container.style.cssText = \`
                position:fixed!important;
                top:0!important;
                left:0!important;
                width:100vw!important;
                height:100vh!important;
                z-index:2147483647!important;
                background:#000!important;
                display:flex!important;
                justify-content:center!important;
                align-items:center!important;
            \`;

            // 克隆视频元素（避免内存泄漏）
            const videoClone = video.cloneNode(true);
            videoClone.style.cssText = \`
                width:100%!important;
                height:auto!important;
                max-width:100%!important;
                max-height:100vh!important;
                object-fit:contain!important;
            \`;
            videoClone.controls = false;
            videoClone.autoplay = true;
            videoClone.muted = false;
            videoClone.volume = 1.0;

            // 构建播放环境
            container.appendChild(videoClone);
            document.body.innerHTML = "";
            document.body.appendChild(container);

            // 播放策略
            const playStrategy = () => {
                videoClone.play().catch(err => {
                    videoClone.muted = true;
                    videoClone.play().catch(() => {
                        container.innerHTML = \`
                            <div style="
                                color:#fff;
                                font-size:24px;
                                position:absolute;
                                top:50%;
                                left:50%;
                                transform:translate(-50%,-50%);
                            ">
                                播放失败，请刷新重试
                            </div>
                        \`;
                    });
                });
            };

            // 延迟启动播放
            setTimeout(playStrategy, 300);
        };

        /* 主循环检测 */
        const detectionLoop = () => {
            if (Date.now() - startTime > MAX_WAIT) {
                document.body.style.visibility = "visible";
                return clearInterval(interval);
            }

            const targetVideo = videoHunter();
            if (targetVideo && targetVideo.readyState > 0) {
                createPlayer(targetVideo);
                clearInterval(interval);
                document.body.style.visibility = "visible";
            }
        };

        // 启动引擎
        initEnv();
        const interval = setInterval(detectionLoop, CHECK_INTERVAL);
    })();
    `;

    // 返回酷9播放参数（修复第133行）
    return JSON.stringify({
        webview: id,
        headers: headers,
        jscode: jscode,
        decode: 1,
        timeout: 20,
        retry: 3,
        setting: {
            "autoPlay": 1,
            "hardwareDecode": 1,
            "userAgent": headers["User-Agent"],
            "cacheControl": "no-cache"
        }
    });
}
